package MyFramePro.Service.Impl;

import MyFramePro.Constants.SystemConstants;
import MyFramePro.Domain.Entity.LoginUser;
import MyFramePro.Domain.Entity.User;
import MyFramePro.Mapper.MenuMapper;
import MyFramePro.Mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.netty.util.internal.ObjectUtil;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 该类是进行重新定义 UserDetailsService 接口，从原本默认的内存查找，更改为从 "数据库" 中进行查找
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private MenuMapper menuMapper;

    /**
     * 重写内部查询认证方法
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据传入的数据进行查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);

        //2.若没有查询到用户，则抛出异常
        if(Objects.isNull(user)){
            throw new RuntimeException("查询失败，当前用户不存在!");
        }

        //TODO 查询权限信息
        //3.如果是后台用户，即管理员，才需要进行查询权限(普通访问的用户不需要校验)，以显示对应的菜单信息
        if(user.getType().equals(SystemConstants.ADMIN)){

            List<String> securityMsgs = menuMapper.selectParmsByUserId(user.getId());    //这里进行查询当前认证用户的权限信息
            return new LoginUser(user,securityMsgs);
        }

        return new LoginUser(user,null);
    }

}
